package authority.servlet;

import authority.comm.Lay;
import authority.comm.Message;
import authority.entity.Role;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@WebServlet("/testServlet")
public class TestServlet extends HttpServlet {
    List<Role> list = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");//获取控制器

        if ("list".equals(opr)) {//
            Lay l = new Lay();
            l.setData(list);
            l.setCount(list.size());
            out.print(JSON.toJSONString(l));
        }

        if ("updateBefore".equals(opr)) {//添加之前
            String id = request.getParameter("id");
            for (Role item : list
                    ) {
                if (item.getId().equals(id)) {
                    out.print(JSON.toJSONString(item));
                    break;
                }
            }

        }

        if ("update".equals(opr)) {
            String id = request.getParameter("id");
            String name = request.getParameter("name");
            for (Role item : list) {
                if (item.getId().equals(id)) {
                    item.setName(name);
                    Message m = new Message();
                    m.setState(true);
                    m.setMeg("修改成功");
                    out.print(JSON.toJSONString(m));
                    break;
                }
            }


        }
    }

    @Override
    public void init() throws ServletException {

        for (int i = 0; i < 10; i++) {
            Role r = new Role();
            r.setId(UUID.randomUUID().toString());
            r.setName("wang");
            list.add(r);
        }


    }
}
